package com.jhd.jiangxi.activity.scan.check;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.google.android.material.tabs.TabLayout;
import com.jhd.jiangxi.R;
import com.jhd.jiangxi.UtilHelper;
import com.jhd.jiangxi.activity.main.BaseActivity;
import com.jhd.jiangxi.activity.scan.BillFragment;
import com.jhd.jiangxi.service.VaccineService;
import com.jhd.jiangxi.util.ListString;
import com.jhd.jiangxi.util.PopWindow;
import com.jhd.jiangxi.service.GetVaccineService;
import com.jhd.jiangxi.util.ScanUtil;
import com.jhd.jiangxi.vo.CheckCode;
import com.jhd.jiangxi.vo.CheckOrderDtlVo;
import com.jhd.jiangxi.vo.CheckOrderMstVo;
import com.jhd.jiangxi.vo.ElectCodePackageVoList;
import com.jhd.jiangxi.vo.Inventory;
import com.jhd.jiangxi.vo.JsonForResult;
import com.jhd.jiangxi.vo.Manufacture;
import com.jhd.jiangxi.vo.StorageInfo;
import com.jhd.jiangxi.vo.UnitPrice;
import com.jhd.jiangxi.vo.VaccineCount;
import com.jhd.jiangxi.vo.VaccineInfo;
import com.jhd.jiangxi.vo.VaccineLots;

import net.zigin.commons.util.ParamsMapUtil;
import net.zigin.commons.util.StringUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/*盘点*/
public class CheckActivity extends BaseActivity implements View.OnClickListener {
    private ViewPager vp;
    private BillFragment billFragment;
    private CheckContentFragment contentFragment;
    private List<Fragment> mDatas = new ArrayList<Fragment>();
    private TabLayout tabs;
    private String[] checkName = {"期初盘点", "日常盘点"};
    private String[] checkId = {"0", "1"};
    private String checkType;
    private String[] categoryName = {"国家免疫规划疫苗", "地方免疫规划疫苗", "应急接种疫苗", "非免疫规划疫苗", "群体性预防接种疫苗", "紧急使用疫苗"};
    private String[] categoryId = {"1", "4", "5", "2", "6", "7"};
    private FragmentPagerAdapter adapter;
    private BarcodeDataReceiver barcodeDataReceiver;
    private AlertDialog _alertDialog = null;
    private final List<String> id = new ArrayList<String>();
    private final List<String> name = new ArrayList<String>();
    List<VaccineCount> vaccineCountList = new ArrayList<>();
    private RecyclerView rvVaccine;
    private Context context = CheckActivity.this;
    private TextView btnSourceType_0, btnType,btnApprovalIn, btnOutDept,btnDeliveryDept,btnStartTime,btnEndTime,btnTransportEquip, btnVaccineType, btnPriceBook, btnToTemp, addStorage;//bill界面:审批人,供货单位,疫苗类型,价格本,下一步
    private Button btnSubmitVaccine, btnDelAllVaccine, btnCountVaccine, btnInput, btnAdd;//content界面:提交,清空,入库明细
    private List<Inventory> inventories = null;//调接口获取到的列表
    private List<Inventory> inventories2 = new ArrayList<>();//判断时候选中显示库存为0的疫苗
    private List<Inventory> searchInventories = new ArrayList<>();//日常盘点搜索到的inventories
    public static List<Inventory> inventoryList = new ArrayList<>();//自己盘点的列表
    private List<VaccineInfo> vaccineInfoList;
    private List<Manufacture> manufactureList;
    private List<VaccineLots> vaccineLotsList;
    private PopupWindow popup;
    private UnitPrice unitPrice;
    private ListView listView;
    private TextView addUnitPrice, addServicePrice, addVaccineName, addManufacturer, addVaccineType, addLotNumber;//添加弹窗的控件
    private TextView startItemVaccineName, startItemFactory, startItemApprovalNo, startItemTotal;
    private RecyclerView startItemRvVaccine;
    private ContentAdapter contentAdapter;
    private Inventory inventory;
    List<ElectCodePackageVoList> electCodeList = new ArrayList<>();
    List<ElectCodePackageVoList> electCodeList2 = new ArrayList<>();
    private CodeAdapter codeAdapter;
    int numberBefore = -1;
    private RecyclerView initialRvVaccine;
    private CheckBox initialCbAllChoose;
    private InitialInputAdapter initialInputAdapter;
    private RecyclerView dailyRvVaccine;
    private EditText dailyEtSearch;
    private DailyInputAdapter dailyInputAdapter;
    private boolean isCheck=false;
    private CheckBox cb_no;//显示库存为0的疫苗

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check);
        popup= new PopupWindow(context);
        openScan(context);
        initView();
        initEvent();
    }

    /*将顶部标题带入,新建俩个fragment*/
    private void initView() {
        initHeader("盘盈入库");
        vp = (ViewPager) findViewById(R.id.vpSheet);
        billFragment = new BillFragment();
        contentFragment = new CheckContentFragment();
        mDatas.add(billFragment);
        mDatas.add(contentFragment);
        tabs = findViewById(R.id.tabSheet);
    }

    @Override
    public void fragmentCreated(View view) {
        super.fragmentCreated(view);
        btnApprovalIn = (TextView) view.findViewById(R.id.btnApprovalIn);
        btnSourceType_0 = (TextView) view.findViewById(R.id.btnSourceType_0);
        btnSourceType_0.setVisibility(View.GONE);
        btnPriceBook = (TextView) view.findViewById(R.id.btnPriceBook);
        btnToTemp = (TextView) view.findViewById(R.id.btnToTemp);
        btnVaccineType = (TextView) view.findViewById(R.id.btnVaccineType);
        btnType = (TextView) view.findViewById(R.id.btnType);
        btnType.setText("盘点类型");
        btnType.setVisibility(View.VISIBLE);
        btnOutDept = (TextView) view.findViewById(R.id.btnOutDept);
        btnOutDept.setVisibility(View.GONE);
        btnDeliveryDept = (TextView) view.findViewById(R.id.btnDeliveryDept);
        btnDeliveryDept.setVisibility(View.GONE);
        btnStartTime = (TextView) view.findViewById(R.id.btnStartTime);
        btnStartTime.setVisibility(View.GONE);
        btnEndTime = (TextView) view.findViewById(R.id.btnEndTime);
        btnEndTime.setVisibility(View.GONE);
        btnTransportEquip = (TextView) view.findViewById(R.id.btnTransportEquip);
        btnTransportEquip.setVisibility(View.GONE);
        addStorage = (TextView) view.findViewById(R.id.btnStorage);
        addStorage.setVisibility(View.GONE);
        btnApprovalIn.setOnClickListener((View.OnClickListener) context);
        btnType.setOnClickListener((View.OnClickListener) context);
        btnPriceBook.setOnClickListener((View.OnClickListener) context);
        btnVaccineType.setOnClickListener((View.OnClickListener) context);
        btnToTemp.setOnClickListener((View.OnClickListener) context);
        getApproval(btnApprovalIn, "盘盈入库");//获取审批人列表
        getPriceBookMst();//获取价格本列表
//        getPerson();//获取盘点人
    }

    @Override
    public void fragmentCreated2(View view) {
        super.fragmentCreated2(view);
        btnSubmitVaccine = (Button) view.findViewById(R.id.btnSubmitVaccine);
        btnDelAllVaccine = (Button) view.findViewById(R.id.btnDelAllVaccine);
        btnCountVaccine = (Button) view.findViewById(R.id.btnCountVaccine);
        btnAdd = (Button) view.findViewById(R.id.btnAdd);
        btnInput = (Button) view.findViewById(R.id.btnInput);
        rvVaccine = (RecyclerView) view.findViewById(R.id.rvVaccine);
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        rvVaccine.setLayoutManager(layoutManager);
        btnAdd.setOnClickListener((View.OnClickListener) context);
        btnInput.setOnClickListener((View.OnClickListener) context);
        btnSubmitVaccine.setOnClickListener((View.OnClickListener) context);
        btnDelAllVaccine.setOnClickListener((View.OnClickListener) context);
        btnCountVaccine.setOnClickListener((View.OnClickListener) context);
    }

    /*点击下一步或者点击扫码入库之前的判断*/
    private void setBtnToTemp() {
        if (btnApprovalIn.getText().toString().equals("审核人")
                || btnVaccineType.getText().toString().equals("疫苗属性") || btnPriceBook.getText().toString().equals("价格本") || btnType.getText().toString().equals("盘点类型")) {
            UtilHelper.alertMsg(context, "请配置好单据页面", "点击任意处关闭弹窗");
            vp.setCurrentItem(0);
        } else {
            String checkVaccineType = application.getCheckVaccineType();
            String checkType = application.getCheckType();
            if (btnVaccineType.getText().toString().equals(checkVaccineType)&&btnType.getText().toString().equals(checkType)) {//疫苗属性或者盘点类型没有变化
                next();
            } else{
                if(inventoryList.size()>0){
                    vp.setCurrentItem(0);
                    isClearDialog();
                }else{
                    vp.setCurrentItem(1);
                    application.setCheckVaccineType(btnVaccineType.getText().toString());
                    application.setCheckType(btnType.getText().toString());
                    next();
                }
                /*if ( ((!"期初盘点".equals(checkType)||)&&(inventories!=null&&inventoryList.size()>0))||(!"日常盘点".equals("checkType")&&inventoryList.size() > 0)) {//说明已经添加过
                    vp.setCurrentItem(0);
                    isClearDialog();
                } else {
                    vp.setCurrentItem(1);
                    application.setCheckVaccineType(btnVaccineType.getText().toString());
                    application.setCheckType(btnType.getText().toString());
                    next();
                }*/
            }

        }
    }

    public void isClearDialog() {
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
        alertBuilder.setTitle("重新盘点");
        alertBuilder.setMessage("疫苗属性或者盘点类型已经重新选过,将会对之前的扫描进行清空，您确定吗?");
        alertBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                application.setCheckVaccineType(btnVaccineType.getText().toString());
                application.setCheckType(btnType.getText().toString());
                electCodeList.clear();
                electCodeList2.clear();
                inventories2.clear();
                clearAll();
                vp.setCurrentItem(1);
                _alertDialog.dismiss();
            }
        });

        alertBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                _alertDialog.dismiss();
            }
        });
        _alertDialog = alertBuilder.create();
        _alertDialog.show();
    }

    private void next() {
        if (vaccineInfoList == null) {
            getVaccinesList();
        }//如果vaccineInfoList为null,获取vaccineInfoList
        if (storageInfoList == null) {
            getStorageInfoList();
        }//如果storageInfoList为null,获取storageInfoList
        if (btnType.getText().toString().equals(checkName[0])) {//"初始盘点",
            btnAdd.setVisibility(View.VISIBLE);
            getInventoryList();
        } else if (btnType.getText().toString().equals(checkName[1])) {//"日常盘点"
            btnAdd.setVisibility(View.GONE);
            getInventoryListForCheck();
        }
    }

    private void initEvent() {
        tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
//                添加选中Tab的逻辑
                if (tab.getPosition() == 1) {
                    setBtnToTemp();
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
//                添加未选中Tab的逻辑
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
//                再次选中tab的逻辑
            }
        });
        adapter = new FragmentPagerAdapter(getSupportFragmentManager(), 1) {
            @Override
            public int getCount() {
                return mDatas.size();
            }

            @Override
            public Fragment getItem(int position) {
                return mDatas.get(position);
            }
        };
        vp.setAdapter(adapter);
        tabs.setupWithViewPager(vp);
        TabLayout.Tab tab = tabs.getTabAt(0);
        ((View) tab.view).setBackgroundResource(R.drawable.tab_left);
        tab.setText("交货单");
        tab = tabs.getTabAt(1);
        ((View) tab.view).setBackgroundResource(R.drawable.tab_right);
        tab.setText("盘点");
    }

    public void openScan(Context context) {//先禁用扫描功能,当需要扫码的时候,打开扫描功能
        barcodeDataReceiver = new BarcodeDataReceiver();
        IntentFilter mFilter = new IntentFilter("nlscan.action.SCANNER_RESULT");
        context.registerReceiver(barcodeDataReceiver, mFilter);
        Intent mIntent = new Intent("ACTION_BAR_SCANCFG");
        mIntent.putExtra("SCAN_INTERVAL", Long.valueOf(3000));
        mIntent.putExtra("EXTRA_TRIG_MODE", 0);// 0 配置扫描头为普通触发模式 /1 配置扫描头为连续扫描模式 /2 配置扫描头为超时扫描模式*
        mIntent.putExtra("EXTRA_SCAN_MODE", 3);// 1 ：直接填充模式* /2 ：虚拟按键模式 /3 ：广播输出模式
        context.sendBroadcast(mIntent);
        Intent mIntent2 = new Intent("ACTION_BAR_SCANCFG");
        mIntent2.putExtra("EXTRA_SCAN_NOTY_SND", 1);
        mIntent2.putExtra("EXTRA_SCAN_NOTY_VIB", 1);
        mIntent2.putExtra("EXTRA_SCAN_POWER", 0);
        sendBroadcast(mIntent2);
    }

    public void closeScan(Context context) {
        context.unregisterReceiver(barcodeDataReceiver);
    }

    class BarcodeDataReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String scanResult_1 = intent.getStringExtra("SCAN_BARCODE1");
            final String scanStatus = intent.getStringExtra("SCAN_STATE");
            if ("ok".equals(scanStatus)) {
                ScanUtil.stopScan(context);
                if (contains(electCodeList, scanResult_1)) {
                    Toast.makeText(context, "该疫苗已经扫描过!", Toast.LENGTH_SHORT).show();
                } else {
                    checkCodeParam(scanResult_1);
                }
            }
        }
    }

    public boolean contains(List<ElectCodePackageVoList> electCodePackageVoLists, String code) {
        for (ElectCodePackageVoList electCodePackageVoList : electCodePackageVoLists) {
            if (electCodePackageVoList.getElectCode().equals(code)) {
                return true;
            }
        }
        return false;
    }

    private List<ElectCodePackageVoList> getPositionElectCodePackageVoList(List<ElectCodePackageVoList> electCodeList) {
        List<ElectCodePackageVoList> list = new ArrayList<>();
        if(electCodeList!=null) {
            for (ElectCodePackageVoList electCodePackageVoList : electCodeList) {
                list.add(electCodePackageVoList);
            }
        }
        return list;
    }

    private void removeElectCodePackageVoList(List<ElectCodePackageVoList> list, ElectCodePackageVoList electCodePackageVoList) {
        if (list.contains(electCodePackageVoList)) {
            list.remove(electCodePackageVoList);
        }
    }

    /*重写返回键*/
    private void back() {
        if (vp.getCurrentItem() == 0) {
            onBackPressed();
        } else if (vp.getCurrentItem() == 1) {
            vp.setCurrentItem(0);//如果是在内容界面点击返回,就回到单据界面
        }
    }

    /*头部的方法,因为返回的功能要重新编写,所以直接重写*/
    protected void initHeader(String title) {
        if ("0".equals(application.getBackSystem())) title = title + "(测试版本)";
        TextView tvTitle = ((TextView) findViewById(R.id.screenTitle));
        if (tvTitle != null) tvTitle.setText(title);
        findViewById(R.id.btnBack).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                back();
            }
        });
        String userName = application.getRealName() == null ? application.getUserName() : application.getRealName();
        ((TextView) findViewById(R.id.tvHeaderUserName)).setText(userName);
    }

    /*重写返回方法,和initHeader一样*/
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            back();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void saveCheckOrderMstAndDtl() {
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        CheckOrderMstVo checkOrderMstVo = new CheckOrderMstVo();
        checkOrderMstVo.setApprovalId(application.getApprovalId());
        checkOrderMstVo.setCategory(application.getCategory());
        checkOrderMstVo.setPriceBookNo(application.getPriceNoIn());
        checkOrderMstVo.setPriceBookMstId(application.getPriceBookMstId());
        checkOrderMstVo.setUserName(application.getRealName() == null ? application.getUserName() : application.getRealName());
        for (int i = 0; i < checkName.length; i++) {
            if (checkName[i].equals(btnType.getText().toString())) {
                checkOrderMstVo.setCheckType(Integer.valueOf(checkId[i]));
            }
        }
        if (application.getRemark() == null) {
            checkOrderMstVo.setRemark("");//备注
        } else {
            checkOrderMstVo.setRemark(application.getRemark());//备注
        }
        List<CheckOrderDtlVo> checkOrderDtlVos = new ArrayList<CheckOrderDtlVo>();
        for (int i = 0; i < inventoryList.size(); i++) {
            CheckOrderDtlVo checkOrderDtlVo = new CheckOrderDtlVo();
            checkOrderDtlVo.setCategory(inventoryList.get(i).getCategory());
            checkOrderDtlVo.setPropertyId(inventoryList.get(i).getPropertyId());
            checkOrderDtlVo.setExpiryDate(inventoryList.get(i).getExpiryDate());
            checkOrderDtlVo.setCheckQuantity(inventoryList.get(i).getCheckNumber());
            checkOrderDtlVo.setLotNumber(inventoryList.get(i).getLotNumber());
            checkOrderDtlVo.setManufacturerId(inventoryList.get(i).getManufacturerId());
            checkOrderDtlVo.setStockQuantity(inventoryList.get(i).getQuantity());
            checkOrderDtlVo.setManufacturerName(inventoryList.get(i).getManufacturerName());
            checkOrderDtlVo.setStorage(inventoryList.get(i).getStorage());
            checkOrderDtlVo.setStorageId(inventoryList.get(i).getStorageId());
            checkOrderDtlVo.setVaccineId(inventoryList.get(i).getVaccineId());
            checkOrderDtlVo.setVaccineName(inventoryList.get(i).getVaccineName());
            checkOrderDtlVo.setVaccineLotsId(inventoryList.get(i).getVaccineLotsId());
            List<CheckCode> checkCodes = new ArrayList<>();
            if(inventoryList.get(i).getElectCodeList()!=null){
                for (ElectCodePackageVoList electCodePackageVoList : inventoryList.get(i).getElectCodeList()) {
                    CheckCode checkCode = new CheckCode();
                    checkCode.setElectCode(electCodePackageVoList.getElectCode());
                    checkCode.setQuantity(Integer.valueOf(electCodePackageVoList.getQuantity()));
                    checkCodes.add(checkCode);
                }
            }
            checkOrderDtlVo.setElectCodePackageVoList(checkCodes);
            checkOrderDtlVos.add(checkOrderDtlVo);
        }
        params.put("deptId", application.getDeptId());
        params.put("checkOrderDtlVoList", checkOrderDtlVos);
        params.put("checkOrderMstVo", checkOrderMstVo);
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.EMIAO(application.getBackSystem()));
        GetVaccineService vs = retrofit.create(GetVaccineService.class);
        String token = application.getAccessToken();
        RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"), JSON.toJSONString(params));
        Call<JsonForResult> jsonForResultCall = vs.saveCheckOrderMstAndDtl(token, requestBody);
        jsonForResultCall.enqueue(new saveCheckOrderMstAndDtl());
    }

    private class saveCheckOrderMstAndDtl implements Callback<JsonForResult> {

        @Override
        public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
            try {
                JsonForResult jsonForResult = (JsonForResult) response.body();
                if (jsonForResult != null && jsonForResult.isSuccess()) {
                    Toast.makeText(context, "盘点成功", Toast.LENGTH_SHORT).show();
                    onBackPressed();
                } else {
                    if (jsonForResult != null && jsonForResult.getMessage() != null && "".equals(jsonForResult.getMessage()) == false) {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                }
            } catch (Exception e) {
                Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<JsonForResult> call, Throwable t) {
            String msg = "网络异常!";
            if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
            UtilHelper.alertMsg(context, "错误", msg);
        }
    }

    /*button的点击监听*/
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            /*case R.id.btnCheckPerson://bill界面点击选择盘点人
                name.clear();
                id.clear();
                if (personList != null) {
                    for (int i = 0; i < personList.size(); i++) {
                        name.add(personList.get(i).getUserName());
                        id.add(personList.get(i).getId());
                    }
                    PopWindow.show(application, context,popup,isCheck, (TextView) v, name, id, 6);
                } else {
                    Toast.makeText(context, "未获取盘点人信息,请稍后重试!", Toast.LENGTH_SHORT).show();
                }
                break;*/
            case R.id.btnVaccineType:
                v.setBackgroundResource(R.drawable.selector_focused);
                PopWindow.show(application, context,popup,isCheck, (TextView) v, Arrays.asList(categoryName), Arrays.asList(categoryId), 2);
                break;
            case R.id.btnToTemp:
                vp.setCurrentItem(1);
                break;
            case R.id.btnApprovalIn://bill界面点击选择审批人
                name.clear();
                id.clear();
                if (approvalList != null) {
                    for (int i = 0; i < approvalList.size(); i++) {
                        name.add(approvalList.get(i).getUserName1());
                        id.add(approvalList.get(i).getId());
                    }
                    PopWindow.show(application, context,popup,isCheck, (TextView) v, name, id, 0);
                } else {
                    Toast.makeText(context, "未获取审批人信息,请稍后重试!", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btnType://bill界面点击选择疫苗类型btnVaccineType
                v.setBackgroundResource(R.drawable.selector_focused);
                PopWindow.show(application, context,popup,isCheck, (TextView) v, Arrays.asList(checkName), Arrays.asList(checkId), 5);
                break;
            case R.id.btnPriceBook://bill界面点击选择价格本
                name.clear();
                id.clear();
                if (priceBook != null) {
                    for (int i = 0; i < priceBook.size(); i++) {
                        name.add(priceBook.get(i).getPriceBookNo());
                        id.add(priceBook.get(i).getId());
                    }
                    PopWindow.show(application, context,popup,isCheck, (TextView) v, name, id, 3);
                } else {
                    Toast.makeText(context, "未获取价格本信息,请稍后重试!", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btnSubmitVaccine://content界面点击保存扫描疫苗
                if (isAllCheck()) {
                    bottomDialog(1, v, "确认提交");
                } else {
                    Toast.makeText(context, "你还有未盘点的疫苗,请先盘点再提交!", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btnDelAllVaccine://content界面点击删除所有扫到的疫苗
                bottomDialog(2, v, "清空扫描");
                break;
            case R.id.btnCountVaccine://content界面点击跳转到汇总界面
                startActivity(new Intent(context, CheckDetailActivity.class));
                break;
            case R.id.btnAdd://跳弹窗,选择除盘点数以外的配置
                addDialog();
                break;
            case R.id.btnInput://跳弹窗,将获取到的inVentoryList展示
                if (btnType.getText().toString().equals(checkName[0])) {
                    initialInputDialog();
                } else if (btnType.getText().toString().equals(checkName[1])) {
                    dailyInputDialog();
                }
                break;
        }
    }

    /*判断是否全部盘点*/
    private boolean isAllCheck() {
        for (Inventory inventory1 : inventoryList) {
            if (inventory1.getCheckNumber() == null) {
                return false;
            }
        }
        return true;
    }

    /*初始盘点点击btnInput*/
    public void initialInputDialog() {
        LayoutInflater mLayoutInflater = LayoutInflater.from(this);
        View view = mLayoutInflater.inflate(R.layout.dialog_check_input_0, null);
        final AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setView(view);
        _alertDialog = alertBuilder.create();
        _alertDialog.show();
        initialCbAllChoose = (CheckBox) view.findViewById(R.id.cbAllChoose);
        initialRvVaccine = (RecyclerView) view.findViewById(R.id.rvVaccine);
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        initialRvVaccine.setLayoutManager(layoutManager);
        if (inventories != null) {
            initialInputAdapter = new InitialInputAdapter(inventories);
            initialRvVaccine.setAdapter(initialInputAdapter);
            initialCbAllChoose.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        for (Inventory inventory : inventories) {
                            inventory.setIsChecked(1);
                        }
                    } else {
                        for (Inventory inventory : inventories) {
                            inventory.setIsChecked(0);
                        }
                    }
                    initialInputAdapter.notifyItemRangeChanged(0, inventories.size());
                }
            });
        }

        TextView tvCancel = (TextView) view.findViewById(R.id.tvCancel);
        TextView tvConfirm = (TextView) view.findViewById(R.id.tvConfirm);
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                _alertDialog.dismiss();
            }
        });
        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<Inventory> list = new ArrayList<>();
                if (inventories != null) {
                    for (Inventory inventory1 : inventories) {
                        if (inventory1.getIsChecked() == 1) {
                            list.add(inventory1);
                        }
                    }
                    initialInputSave(list);//删除inventories中选中的数据,判断inventoryList中是否存在该数据,不存在则加入
                }
                _alertDialog.dismiss();
            }
        });
    }

    /*日常盘点点击btnInput*/
    public void dailyInputDialog() {
        LayoutInflater mLayoutInflater = LayoutInflater.from(this);
        View view = mLayoutInflater.inflate(R.layout.dialog_check_input_1, null);
        final AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setView(view);
        _alertDialog = alertBuilder.create();
        _alertDialog.show();
        dailyRvVaccine = (RecyclerView) view.findViewById(R.id.rvVaccine);
        dailyEtSearch = (EditText) view.findViewById(R.id.etSearch);
        cb_no = (CheckBox) view.findViewById(R.id.cb_no);
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        dailyRvVaccine.setLayoutManager(layoutManager);
        if(inventories!=null){
            inventories2.clear();
            for (Inventory inventory1 : inventories) {
                if(inventory1.getQuantity()!=0){
                    inventories2.add(inventory1);
                }
            }
            dailyInputAdapter = new DailyInputAdapter(inventories2);
            dailyRvVaccine.setAdapter(dailyInputAdapter);
        }
        cb_no.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    inventories2.clear();
                    if(inventories!=null){
                        for (Inventory inventory1 : inventories) {
                            inventories2.add(inventory1);
                        }
                    }
                }else {
                    inventories2.clear();
                    if(inventories!=null){
                        for (Inventory inventory1 : inventories) {
                            if(inventory1.getQuantity()!=0){
                                inventories2.add(inventory1);
                            }
                        }
                    }
                }
                dailyInputAdapter = new DailyInputAdapter(inventories2);
                dailyRvVaccine.setAdapter(dailyInputAdapter);
            }
        });
        dailyEtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String name = s.toString().trim();
                searchInventories.clear();
                    if (inventories2 != null) {
                        for (Inventory inventory : inventories2) {
                            if (inventory.getVaccineName().contains(name)) {
                                searchInventories.add(inventory);
                            }
                        }
                    }
                    dailyInputAdapter = new DailyInputAdapter(searchInventories);
                    dailyRvVaccine.setAdapter(dailyInputAdapter);
            }
        });
        TextView tvCancel = (TextView) view.findViewById(R.id.tvCancel);
        TextView tvConfirm = (TextView) view.findViewById(R.id.tvConfirm);
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                _alertDialog.dismiss();
            }
        });
        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<Inventory> list = new ArrayList<>();
                if(inventories!=null){
                    for (Inventory inventory1 : inventories) {
                        if (inventory1.getCheckNumber() != null) {
                            list.add(inventory1);
                            inventoryList.add(0, inventory1);
                            if (inventoryList.size() == 1) {
                                contentAdapter = new ContentAdapter(inventoryList);
                                rvVaccine.setAdapter(contentAdapter);
                            } else {
                                contentAdapter.notifyItemInserted(0);
                                contentAdapter.notifyItemRangeChanged(0, inventoryList.size());
                            }
                        }
                    }
                    for (Inventory inventory1 : list) {
                        if (inventories.contains(inventory1)) {
                            inventories.remove(inventory1);
                        }
                    }
                }
                _alertDialog.dismiss();
            }
        });
    }


    /*期初盘点选中item的弹窗*/
    public void startItemDialog(int index) {
        inventory = inventoryList.get(index);
        LayoutInflater mLayoutInflater = LayoutInflater.from(this);
        View view = mLayoutInflater.inflate(R.layout.dialog_check_code, null);
        final AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setView(view);
        _alertDialog = alertBuilder.create();
        _alertDialog.show();_alertDialog.setCanceledOnTouchOutside(false);
        ScanUtil.powerOnScan(context);
        startItemVaccineName = (TextView) view.findViewById(R.id.tvVaccineName);
        startItemFactory = (TextView) view.findViewById(R.id.tvFactory);
        startItemApprovalNo = (TextView) view.findViewById(R.id.tvApprovalNo);
        startItemTotal = (TextView) view.findViewById(R.id.tvTotal);
        startItemRvVaccine = (RecyclerView) view.findViewById(R.id.rvVaccine);
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        startItemRvVaccine.setLayoutManager(layoutManager);
        startItemVaccineName.setText(inventory.getVaccineName());
        startItemFactory.setText(inventory.getManufacturerName());
        startItemApprovalNo.setText(inventory.getLotNumber());
        if (getPositionElectCodePackageVoList(inventory.getElectCodeList()).size() > 0) {
            codeAdapter = new CodeAdapter(getPositionElectCodePackageVoList(inventory.getElectCodeList()));
            startItemRvVaccine.setAdapter(codeAdapter);
            int num = 0;
            for (ElectCodePackageVoList electCodePackageVoList : getPositionElectCodePackageVoList(inventory.getElectCodeList())) {
                num = num + Integer.valueOf(electCodePackageVoList.getQuantity());
            }
            startItemTotal.setText(String.valueOf(num));
        }
        TextView tvCancel = (TextView) view.findViewById(R.id.tvCancel);
        TextView tvConfirm = (TextView) view.findViewById(R.id.tvConfirm);
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                removeElectCodeList2();
                _alertDialog.dismiss();
                ScanUtil.powerOffScan(context);
            }
        });
        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int num = 0;
                for (ElectCodePackageVoList electCodePackageVoList : getPositionElectCodePackageVoList(electCodeList2)) {
                    num = num + Integer.valueOf(electCodePackageVoList.getQuantity());
                }
                inventory.setElectCodeList(getPositionElectCodePackageVoList(electCodeList2));
                if (getPositionElectCodePackageVoList(electCodeList2).size() == 0) {
                    inventory.setCheckNumber(null);
                } else {
                    inventory.setCheckNumber(num);
                }
                contentAdapter.notifyDataSetChanged();
                ScanUtil.powerOffScan(context);
                electCodeList2.clear();
                _alertDialog.dismiss();
            }
        });

    }

    /*删除inventories中选中的数据,判断inventoryList中是否存在该数据,不存在则加入*/
    private void initialInputSave(List<Inventory> list) {
        for (Inventory inventory1 : list) {
            inventories.remove(inventory1);//获取的列表将数据清除
            if (!containsInventory(inventory1)) {//inventoryList可能包含相同的数据,因为electCodeList可能不一样,不能直接用contains方法
                inventory1.setIsChecked(0);//将选中值赋值回0,以便删除时直接加入inventories
                inventory1.setCheckNumber(null);
                inventoryList.add(0, inventory1);
            }
        }
        if(contentAdapter==null){
            contentAdapter = new ContentAdapter(inventoryList);
            rvVaccine.setAdapter(contentAdapter);
        }else{
            contentAdapter.notifyItemInserted(0);
            contentAdapter.notifyItemRangeChanged(0, inventoryList.size());//更新的位置,更新的总条数
        }
    }

    /*本次扫描没有保存,直接退出*/
    private boolean containsInventory(Inventory inventory) {
        for (Inventory inventory1 : inventoryList) {
            if (inventory1.getVaccineName().equals(inventory.getVaccineName()) && inventory1.getStorageId().equals(inventory.getStorageId())
                    && inventory1.getManufacturerId().equals(inventory.getManufacturerId()) && inventory1.getCategory().equals(inventory.getCategory())
                    && inventory1.getExpiryDate().equals(inventory.getExpiryDate()) && inventory1.getUnitPrice() == inventory.getUnitPrice() && inventory1.getServicePrice() == inventory.getServicePrice()
                    && inventory1.getVaccineSpec().equals(inventory.getVaccineSpec()) && inventory1.getVaccineDose().equals(inventory.getVaccineDose()) && inventory1.getQuantityOfSpec() == inventory.getQuantityOfSpec()) {
                return true;
            }
        }
        return false;
    }

    /*本次扫描没有保存,直接退出*/
    private void removeElectCodeList2() {
        for (ElectCodePackageVoList electCodePackageVoList : electCodeList2) {
            electCodeList.remove(electCodePackageVoList);
        }
        electCodeList2.clear();
    }

    /*添加按键跳得弹窗*/
    public void addDialog() {
        LayoutInflater mLayoutInflater = LayoutInflater.from(this);
        View view = mLayoutInflater.inflate(R.layout.dialog_check_add, null);
        final AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setView(view);
        _alertDialog = alertBuilder.create();
        _alertDialog.show();
        addVaccineName = (TextView) view.findViewById(R.id.tvVaccineName);
        addManufacturer = (TextView) view.findViewById(R.id.btnManufacturer);
        addLotNumber = (TextView) view.findViewById(R.id.btnLotNumber);
        addVaccineType = (TextView) view.findViewById(R.id.btnVaccineType);
        addStorage = (TextView) view.findViewById(R.id.btnStorage);
        addUnitPrice = (TextView) view.findViewById(R.id.tvUnitPrice);
        addServicePrice = (TextView) view.findViewById(R.id.tvServicePrice);
        TextView tvCancel = (TextView) view.findViewById(R.id.tvCancel);
        TextView tvConfirm = (TextView) view.findViewById(R.id.tvConfirm);
        addVaccineType.setText(btnVaccineType.getText().toString());
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                _alertDialog.dismiss();
            }
        });
        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (addVaccineName.getText().toString().equals("疫苗名称") || addManufacturer.getText().toString().equals("生产厂家") || addLotNumber.getText().toString().equals("批号") || addStorage.getText().toString().equals("储位")) {
                    Toast.makeText(context, "请将配置都选好!", Toast.LENGTH_SHORT).show();
                } else {
                    VaccineLots vaccineLots = ListString.str2Lots(application.getVaccineLots());
                    Inventory inventory = new Inventory();
                    inventory.setCategory(application.getCategory());
                    inventory.setVaccineName(addVaccineName.getText().toString());
                    inventory.setVaccineId(application.getVaccineId());
                    inventory.setUnitPrice(Integer.valueOf(addUnitPrice.getText().toString().substring(3)));
                    inventory.setServicePrice(Integer.valueOf(addServicePrice.getText().toString().substring(4)));
                    inventory.setManufacturerName(addManufacturer.getText().toString());
                    inventory.setManufacturerId(application.getManufacturerId());
                    inventory.setLotNumber(application.getLotNumber());
                    inventory.setCategory(application.getCategory());
                    inventory.setStorage(application.getStorageName());
                    inventory.setStorageId(application.getStorageId());
                    inventory.setVaccineDose(vaccineLots.getVaccineDose());
                    inventory.setVaccineSpec(vaccineLots.getVaccineSpec());
                    inventory.setVaccineLotsId(vaccineLots.getId());
                    inventory.setPropertyId(vaccineLots.getPropertyId());
                    inventory.setQuantity(0);//库存
                    inventory.setExpiryDate(vaccineLots.getExpiryDate());
                    inventory.setQuantityOfSpec(vaccineLots.getQuantityOfSpec());
                    if (!contains(inventoryList, inventory)) {
                        inventoryList.add(0, inventory);
                    }
                    if (inventoryList.size() == 1) {
                        contentAdapter = new ContentAdapter(inventoryList);
                        rvVaccine.setAdapter(contentAdapter);
                    } else {
                        contentAdapter.notifyItemInserted(0);
                        contentAdapter.notifyItemRangeChanged(0, inventoryList.size());//更新的位置,更新的总条数
                    }
                    _alertDialog.dismiss();
                }
            }
        });
        addStorage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                name.clear();
                id.clear();
                if (storageInfoList != null) {
                    for (StorageInfo storageInfo : storageInfoList) {
                        name.add(storageInfo.getName());
                        id.add(storageInfo.getId());
                    }
                    pupDropDown(addStorage, name, id, null);
                } else {
                    Toast.makeText(context, "未获取到储位列表!", Toast.LENGTH_SHORT).show();
                }
            }
        });
        addVaccineName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                name.clear();
                id.clear();
                if (vaccineInfoList != null) {
                    for (VaccineInfo vaccineInfo : vaccineInfoList) {
                        name.add(vaccineInfo.getName());
                        id.add(vaccineInfo.getGlobeVaccineId());
                    }
                    pupDropDown(addVaccineName, name, id, null);
                } else {
                    Toast.makeText(context, "未获取到疫苗列表!", Toast.LENGTH_SHORT).show();
                }
            }
        });
        addManufacturer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                name.clear();
                id.clear();
                if (manufactureList != null) {
                    for (Manufacture manufacture : manufactureList) {
                        name.add(manufacture.getNameShort());
                        id.add(manufacture.getId());
                    }
                    pupDropDown(addManufacturer, name, id, null);
                } else {
                    Toast.makeText(context, "未获取到生厂厂家列表!", Toast.LENGTH_SHORT).show();
                }
            }
        });
        addLotNumber.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                name.clear();
                id.clear();
                if (vaccineLotsList != null) {
                    for (VaccineLots vaccineLots : vaccineLotsList) {
                        name.add(vaccineLots.getLotNumber());
                        id.add(vaccineLots.getPropertyId());
                    }
                    pupDropDown(addLotNumber, name, id, vaccineLotsList);
                } else {
                    Toast.makeText(context, "未获取到批号列表!", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void pupDropDown(TextView textView, List<String> name, List<String> id, List<VaccineLots> vaccineLotsList) {
        listView = new ListView(context);
        listView.setDivider(null);//设置分割线
        listView.setVerticalScrollBarEnabled(false);//不显示滑动条
        listView.setAdapter(new PupDropDownAdapter(textView, name, id, vaccineLotsList));
        popup = new PopupWindow(context);
        popup.setWidth(textView.getWidth());
        popup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.selector_unfocused));
        popup.setContentView(listView);//设置显示内容
        popup.setOutsideTouchable(true);//点击PopupWindow以外的区域自动关闭该窗口
        popup.showAsDropDown(textView, 0, 5);//显示在edit控件的下面0,0代表偏移量
        textView.setBackgroundResource(R.drawable.selector_focused);
        popup.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                textView.setBackgroundResource(R.drawable.selector_unfocused);
            }
        });
    }

    private boolean contains(List<Inventory> inventoryList, Inventory inventory) {
        for (Inventory inventory1 : inventoryList) {
            if (inventory.getVaccineName().equals(inventory1.getVaccineName()) && inventory.getStorageId().equals(inventory1.getStorageId()) && inventory.getManufacturerId().equals(inventory1.getManufacturerId())) {
                Toast.makeText(context, "已存在疫苗名称,储位,生产厂家相同的数据,不可添加!", Toast.LENGTH_SHORT).show();
                return true;
            }
        }
        return false;
    }

    //适配器
    private class PupDropDownAdapter extends BaseAdapter {
        private List<String> name, id;
        private TextView textView;
        private List<VaccineLots> vaccineLotsList;

        public PupDropDownAdapter(TextView textView, List<String> name, List<String> id, List<VaccineLots> vaccineLotsList) {
            this.name = name;
            this.id = id;
            this.textView = textView;
            this.vaccineLotsList = vaccineLotsList;
        }

        @Override
        public int getCount() {
            return name.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            HolderView holderView = null;
            if (convertView == null) {
                convertView = View.inflate(context, R.layout.item_dialog_login, null);
                holderView = new HolderView();
                holderView.text = (TextView) convertView.findViewById(R.id.tvStorage);
                convertView.setTag(holderView);
            } else {
                holderView = (HolderView) convertView.getTag();
            }

            holderView.text.setText(name.get(position));
            holderView.text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String ss = addVaccineName.getText().toString();
                    textView.setText(name.get(position));
                    textView.setTextColor(getResources().getColor(R.color.billTextChoose));
                    notifyDataSetChanged();
                    textView.setBackgroundResource(R.drawable.selector_unfocused);
                    popup.dismiss();
                    //addUnitPrice, addServicePrice,addVaccineName,addManufacturer,addVaccineType,addLotNumber;
                    if (textView == addVaccineName) {//疫苗名称
                        if (!ss.equals(name.get(position))) {
                            addManufacturer.setText("生产厂家");
                            addManufacturer.setTextColor(getResources().getColor(R.color.billText));
                            addLotNumber.setText("批号");
                            addLotNumber.setTextColor(getResources().getColor(R.color.billText));
                            addUnitPrice.setText("单价");
                            addUnitPrice.setTextColor(getResources().getColor(R.color.billText));
                            addServicePrice.setText("服务费");
                            addServicePrice.setTextColor(getResources().getColor(R.color.billText));
                        }
                        application.setVaccineId(id.get(position));
                        getGlobeManufacturesListFromManufacturesVaccineInfo();
                    } else if (textView == addManufacturer) {//生产厂家
                        application.setManufacturerId(id.get(position));
                        getVaccineLotsList();
                    } else if (textView == addLotNumber) {//批号
                        application.setVaccineLots(ListString.lots2Str(vaccineLotsList.get(position)));
                        application.setPropertyId(id.get(position));
                        application.setLotNumber(name.get(position));
                        getUnitPriceByType(addServicePrice, addUnitPrice);
                    } else if (textView == addStorage) {//代表储位
                        application.setStorageId(id.get(position));
                        application.setStorageName(name.get(position));
                    }
                }
            });
            return convertView;
        }

        public class HolderView {//由于这里用户都是同一个人,就省略用户图像的刷新
            private TextView text;
        }
    }

    public class DailyInputAdapter extends RecyclerView.Adapter<DailyInputAdapter.ViewHolder> {
        private List<Inventory> inventories;

        public DailyInputAdapter(List<Inventory> inventories) {
            this.inventories = inventories;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item__check_1, parent, false);
            ViewHolder viewHolder = new ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            holder.tvVaccineName.setText(inventories.get(position).getVaccineName());
            holder.tvFactory.setText(inventories.get(position).getManufacturerName());
            holder.tvApprovalNo.setText(inventories.get(position).getLotNumber());
            holder.tvExpireDate.setText(inventories.get(position).getExpiryDate());
            holder.tvStorage.setText(inventories.get(position).getStorage());
            holder.tvNumber.setText(String.valueOf(inventories.get(position).getQuantity()));
            holder.etCheckNumber.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (!s.toString().equals("")) {
                        inventories.get(position).setCheckNumber(Integer.parseInt(s.toString()));
                    } else {
                        inventories.get(position).setCheckNumber(null);
                    }
                }
            });
        }

        @Override
        public int getItemCount() {
            return inventories.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tvVaccineName, tvFactory, tvApprovalNo, tvNumber; //疫苗名称，生产厂家，批号,库存数
            TextView tvExpireDate, tvStorage; // 效期,储位
            EditText etCheckNumber;

            public ViewHolder(View itemView) {
                super(itemView);
                this.tvVaccineName = itemView.findViewById(R.id.tvVaccineName);
                this.tvFactory = itemView.findViewById(R.id.tvFactory);
                this.tvApprovalNo = itemView.findViewById(R.id.tvApprovalNo);
                this.tvStorage = itemView.findViewById(R.id.tvStorage);
                this.tvExpireDate = itemView.findViewById(R.id.tvExpireDate);
                this.tvNumber = itemView.findViewById(R.id.tvNumber);
                this.etCheckNumber = itemView.findViewById(R.id.etCheckNumber);
            }
        }
    }

    public class InitialInputAdapter extends RecyclerView.Adapter<InitialInputAdapter.ViewHolder> {
        private List<Inventory> inventories;

        public InitialInputAdapter(List<Inventory> inventories) {
            this.inventories = inventories;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item__check_0, parent, false);
            ViewHolder viewHolder = new ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            holder.tvVaccineName.setText(inventories.get(position).getVaccineName());
            holder.tvFactory.setText(inventories.get(position).getManufacturerName());
            holder.tvApprovalNo.setText(inventories.get(position).getLotNumber());
            holder.tvExpireDate.setText(inventories.get(position).getExpiryDate());
            holder.tvStorage.setText(inventories.get(position).getStorage());
            holder.tvNumber.setText(String.valueOf(inventories.get(position).getQuantity()));
            if (inventories.get(position).getIsChecked() == 1) {
                holder.cbChoose.setChecked(true);
            } else {
                holder.cbChoose.setChecked(false);
            }
            holder.cbChoose.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        holder.cbChoose.setChecked(true);
                        application.setVaccineId(inventories.get(position).getVaccineId());
                        application.setManufacturerId(inventories.get(position).getManufacturerId());
                        application.setVaccineLots(inventories.get(position).getVaccineLotsId());
                        application.setStorageId(inventories.get(position).getStorageId());
                        application.setStorageName(inventories.get(position).getStorage());
                        application.setPropertyId(inventories.get(position).getPropertyId());
                        application.setLotNumber(inventories.get(position).getLotNumber());
                        inventories.get(position).setIsChecked(1);
                    } else {
                        holder.cbChoose.setChecked(false);
                        inventories.get(position).setIsChecked(0);
                    }
                }
            });

        }

        @Override
        public int getItemCount() {
            return inventories.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tvVaccineName, tvFactory, tvApprovalNo, tvNumber; //疫苗名称，生产厂家，批号,库存数
            TextView tvExpireDate, tvStorage; // 效期,储位
            CheckBox cbChoose;

            public ViewHolder(View itemView) {
                super(itemView);
                this.tvVaccineName = itemView.findViewById(R.id.tvVaccineName);
                this.tvFactory = itemView.findViewById(R.id.tvFactory);
                this.cbChoose = itemView.findViewById(R.id.cbChoose);
                this.tvApprovalNo = itemView.findViewById(R.id.tvApprovalNo);
                this.tvStorage = itemView.findViewById(R.id.tvStorage);
                this.tvExpireDate = itemView.findViewById(R.id.tvExpireDate);
                this.tvNumber = itemView.findViewById(R.id.tvNumber);
            }
        }
    }

    private class ContentAdapter extends RecyclerView.Adapter<ContentAdapter.ViewHolder> {
        private List<Inventory> inventoryList;

        public ContentAdapter(List<Inventory> inventoryList) {
            this.inventoryList = inventoryList;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_vaccine_check, parent, false);
            ViewHolder viewHolder = new ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            holder.tvVaccineName.setText(inventoryList.get(position).getVaccineName());
            holder.tvFactory.setText(inventoryList.get(position).getManufacturerName());
            holder.tvApprovalNo.setText(inventoryList.get(position).getLotNumber());
            holder.tvVaccineDose.setText(inventoryList.get(position).getVaccineDose() + "/" + inventoryList.get(position).getVaccineSpec());
            holder.tvExpireDate.setText(inventoryList.get(position).getExpiryDate());
            holder.tvUnitPrice.setText(String.valueOf(inventoryList.get(position).getUnitPrice()));
            holder.tvServicePrice.setText(String.valueOf(inventoryList.get(position).getServicePrice()));
            holder.tvStorage.setText(inventoryList.get(position).getStorage());
            holder.tvNumber.setText(String.valueOf(inventoryList.get(position).getQuantity()));
            if("期初盘点".equals(application.getCheckType())){
                holder.tvCheckNumber.setFocusable(false);
            }else{
                holder.tvCheckNumber.setFocusable(true);
            }
            if ((Integer) inventoryList.get(position).getCheckNumber() != null) {//不为空的时候,显示数据
                holder.tvCheckNumber.setText(String.valueOf(inventoryList.get(position).getCheckNumber()));
            } else {
                holder.tvCheckNumber.setText("");
            }
            holder.tvCheckNumber.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    if(position<inventoryList.size()) {
                        holder.tvCheckNumber.setSelection(s.toString().length());
                        if(s.toString().equals("")){
                            holder.tvCheckNumber.setText("0");
                            inventoryList.get(position).setCheckNumber(0);
                        }else{
                            if(s.toString().length()>1&&s.toString().startsWith("0")){
                                holder.tvCheckNumber.setText(s.toString().substring(1));
                            }
                            inventoryList.get(position).setCheckNumber(Integer.valueOf(s.toString()));
                        }
                    }
                }
            });
            holder.linearLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //点击这个跳弹窗,分情况"初始盘点", "日常盘点"};
                    if (btnType.getText().toString().equals(checkName[0])) {//日常盘点点击没有操作
                        startItemDialog(position);
                    }
                }
            });
            holder.iv_del.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //将该item删除
                    removeItem(inventoryList.get(position).getElectCodeList());
                    inventoryList.get(position).setCheckNumber(null);
                    inventories.add(0, inventoryList.get(position));
                    inventoryList.remove(position);
                    notifyItemRemoved(position);//移除该位置的项目
                    notifyItemRangeChanged(position, getItemCount() - position);//局部刷新从该position位置开始到剩余的所有项目
                    notifyDataSetChanged();
                    electCodeList.size();
                }
            });
        }

        @Override
        public int getItemCount() {
            return inventoryList.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            EditText tvCheckNumber;//盘点数
            TextView tvVaccineName, tvFactory, tvApprovalNo, tvNumber ; //疫苗名称，生产厂家，批号,库存数,
            TextView tvVaccineDose, tvExpireDate, tvUnitPrice, tvServicePrice, tvStorage; // 计量规格,效期,单价,服务费,储位
            ImageView iv_del;
            LinearLayout linearLayout;

            public ViewHolder(View itemView) {
                super(itemView);
                this.tvVaccineName = itemView.findViewById(R.id.tvVaccineName);
                this.tvFactory = itemView.findViewById(R.id.tvFactory);
                this.iv_del = itemView.findViewById(R.id.iv_del);
                this.tvApprovalNo = itemView.findViewById(R.id.tvApprovalNo);
                this.tvVaccineDose = itemView.findViewById(R.id.tvVaccineDose);
                this.tvExpireDate = itemView.findViewById(R.id.tvExpireDate);
                this.tvUnitPrice = itemView.findViewById(R.id.tvUnitPrice);
                this.tvServicePrice = itemView.findViewById(R.id.tvServicePrice);
                this.tvStorage = itemView.findViewById(R.id.tvStorage);
                this.tvNumber = itemView.findViewById(R.id.tvNumber);
                this.tvCheckNumber = itemView.findViewById(R.id.tvCheckNumber);
                this.linearLayout = itemView.findViewById(R.id.linearLayout);
            }
        }
    }

    private void removeItem(List<ElectCodePackageVoList> electCodeList2) {
        List<ElectCodePackageVoList> list = new ArrayList<>();
        if(electCodeList2!=null) {
            for (ElectCodePackageVoList codePackageVoList : electCodeList2) {
                list.add(codePackageVoList);
            }
        }
        for (ElectCodePackageVoList electCodePackageVoList : list) {
            electCodeList.remove(electCodePackageVoList);
        }
    }

    public class CodeAdapter extends RecyclerView.Adapter<CodeAdapter.ViewHolder> {
        private List<ElectCodePackageVoList> electCodePackageVoList;

        public CodeAdapter(List<ElectCodePackageVoList> electCodePackageVoList) {
            this.electCodePackageVoList = electCodePackageVoList;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_check_code, parent, false);
            ViewHolder viewHolder = new ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            holder.tv_electCode.setText(electCodePackageVoList.get(position).getElectCode());
            holder.et_num.setText(electCodePackageVoList.get(position).getQuantity());
            int num = 0;
            for (ElectCodePackageVoList codePackageVoList : electCodePackageVoList) {
                if (!codePackageVoList.getQuantity().trim().equals("")) {
                    num = num + Integer.parseInt(codePackageVoList.getQuantity());
                }
            }
            startItemTotal.setText(String.valueOf(num));
            inventory.setCheckNumber(num);
            holder.et_num.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    if (!s.toString().equals("")) {
                        numberBefore = Integer.valueOf(s.toString());
                    }
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    if (!s.toString().equals("")) {
                        int ss = Integer.valueOf(s.toString());
                        if (ss > inventory.getQuantityOfSpec()) {
                            Toast.makeText(context, "输入有误,不能大于包装值!", Toast.LENGTH_SHORT).show();
                            holder.et_num.setText(String.valueOf(numberBefore));
                            holder.et_num.setSelection(String.valueOf(numberBefore).length() - 1);
                        }
                    } else {
                        holder.et_num.setText("0");
                        holder.et_num.setSelection(0);
                    }

                }

                @Override
                public void afterTextChanged(Editable s) {
                    electCodePackageVoList.get(position).setQuantity(holder.et_num.getText().toString());
                    int num = 0;
                    for (ElectCodePackageVoList codePackageVoList : electCodePackageVoList) {
                        if (!codePackageVoList.getQuantity().trim().equals("")) {
                            num = num + Integer.parseInt(codePackageVoList.getQuantity());
                        }
                    }
                    startItemTotal.setText(String.valueOf(num));
                    inventory.setCheckNumber(num);
                }
            });
            holder.tv_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //将该item删除
                    removeElectCodePackageVoList(electCodeList, electCodePackageVoList.get(position));
                    removeElectCodePackageVoList(electCodeList2, electCodePackageVoList.get(position));
                    electCodePackageVoList.remove(position);
                    notifyItemRemoved(position);//移除该位置的项目
                    notifyItemRangeChanged(position, getItemCount() - position);//局部刷新从该position位置开始到剩余的所有项目
                    int num = 0;
                    for (ElectCodePackageVoList codePackageVoList : electCodePackageVoList) {
                        if (!codePackageVoList.getQuantity().trim().equals("")) {
                            num = num + Integer.parseInt(codePackageVoList.getQuantity());
                        }
                    }
                    startItemTotal.setText(String.valueOf(num));
                    if (electCodePackageVoList.size() == 0) {
                        inventory.setCheckNumber(null);
                    } else {
                        inventory.setCheckNumber(num);
                    }
                }
            });
        }

        @Override
        public int getItemCount() {
            return electCodePackageVoList.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tv_electCode, tv_delete;
            EditText et_num;

            public ViewHolder(View itemView) {
                super(itemView);
                this.tv_electCode = itemView.findViewById(R.id.tv_electCode);
                this.tv_delete = itemView.findViewById(R.id.tv_delete);
                this.et_num = itemView.findViewById(R.id.et_num);
            }
        }
    }

    /*底部按键跳得弹窗*/
    public void bottomDialog(int dex, View v, String title) {
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(v.getContext());
        alertBuilder.setTitle(title);
        if (title.equals("确认提交")) {
            String msg = "";
            vaccineCountList.clear();
            for (Inventory inventory : inventoryList) {
                VaccineCount vaccineCount = new VaccineCount();
                vaccineCount.setName(inventory.getVaccineName());
                if (!vaccineCountList.contains(vaccineCount)) {
                    vaccineCountList.add(vaccineCount);
                }
            }
            for (VaccineCount vaccineCount : vaccineCountList) {
                int num = 0;
                for (Inventory inventory : inventoryList) {
                    if (inventory.getVaccineName().equals(vaccineCount.getName())) {
                        num = num + inventory.getCheckNumber();
                    }
                }
                vaccineCount.setNum(num);
            }
            for (int i = 0; i < vaccineCountList.size(); i++) {
                msg = msg + "疫苗名称:" + vaccineCountList.get(i).getName() + " 盘点数:" + vaccineCountList.get(i).getNum() + "\n";
            }
            alertBuilder.setMessage("已盘点疫苗 " + msg + "你确定保存盘点信息吗?");
        } else if (title.equals("清空扫描")) {
            alertBuilder.setIcon(R.mipmap.dialog_alert);
            alertBuilder.setMessage("你确定清空所有已盘点疫苗吗");
        }
        alertBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (dex == 1) {//保存所有数据
                    saveCheckOrderMstAndDtl();
                } else if (dex == 2) {//清空储位数据
                    clearAll();
                }
                _alertDialog.dismiss();
            }
        });

        alertBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                _alertDialog.dismiss();
            }
        });
        _alertDialog = alertBuilder.create();
        _alertDialog.show();
    }

    private void clearAll() {
        for (Inventory inventory1 : inventoryList) {
            inventory1.setCheckNumber(null);
            inventories.add(0, inventory1);
        }
        inventoryList.clear();
        ContentAdapter contentAdapter = new ContentAdapter(inventoryList);
        rvVaccine.setAdapter(contentAdapter);
    }

    /*期初盘点获取导入库存*/
    private void getInventoryList() {
        String baseUrl = UtilHelper.baseUrls.EMIAO(application.getBackSystem());
        Retrofit retrofit = UtilHelper.retrofit(application, baseUrl);
        Map<String, String> params = ParamsMapUtil.getInstance("deptId", application.getDeptId()).addParam("category", application.getCategory());
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = null;
        VaccineService vs = retrofit.create(VaccineService.class);
        jsonForResultCall = vs.getInventoryList(token, params);
        jsonForResultCall.enqueue(new getInventoryListCallback());
    }

    private class getInventoryListCallback implements Callback<JsonForResult> {
        @Override
        public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
            try {
                JsonForResult jsonForResult = (JsonForResult) response.body();
                if (jsonForResult != null && jsonForResult.isSuccess() && jsonForResult.getData() != null) {
                    inventories = JSON.parseArray(jsonForResult.getData().toString(), Inventory.class);
                } else {
                    if (jsonForResult != null && jsonForResult.getMessage() != null && "".equals(jsonForResult.getMessage()) == false) {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                }
            } catch (Exception e) {
                Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<JsonForResult> call, Throwable t) {
            String msg = "获取数据失败!";
            if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
            Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
        }
    }

    /*日常盘点获取导入库存*/
    private void getInventoryListForCheck() {
        String baseUrl = UtilHelper.baseUrls.EMIAO(application.getBackSystem());
        Retrofit retrofit = UtilHelper.retrofit(application, baseUrl);
        Map<String, String> params = ParamsMapUtil.getInstance("deptId", application.getDeptId()).addParam("category", application.getCategory());
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = null;
        VaccineService vs = retrofit.create(VaccineService.class);
        jsonForResultCall = vs.getInventoryListForCheck(token, params);
        jsonForResultCall.enqueue(new getInventoryListForCheckCallback());
    }

    private class getInventoryListForCheckCallback implements Callback<JsonForResult> {
        @Override
        public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
            try {
                JsonForResult jsonForResult = (JsonForResult) response.body();
                if (jsonForResult != null && jsonForResult.isSuccess() && jsonForResult.getData() != null) {
                    inventories = JSON.parseArray(jsonForResult.getData().toString(), Inventory.class);
                } else {
                    if (jsonForResult != null && jsonForResult.getMessage() != null && "".equals(jsonForResult.getMessage()) == false) {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                }
            } catch (Exception e) {
                Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<JsonForResult> call, Throwable t) {
            String msg = "获取数据失败!";
            if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
            Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
        }
    }

    /*获取疫苗的列表*/
    private void getVaccinesList() {
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("deptId", application.getDeptId());
        params.put("category", application.getCategory());
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.EMIAO(application.getBackSystem()));
        VaccineService vs = retrofit.create(VaccineService.class);
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = vs.getVaccinesList(token, params);
        jsonForResultCall.enqueue(new getVaccinesListCallback());
    }

    private class getVaccinesListCallback implements Callback<JsonForResult> {

        @Override
        public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
            try {
                JsonForResult jsonForResult = (JsonForResult) response.body();
                if (jsonForResult != null && jsonForResult.isSuccess() && jsonForResult.getData() != null) {
                    vaccineInfoList = JSON.parseArray(jsonForResult.getData().toString(), VaccineInfo.class);
                } else {
                    if (jsonForResult != null && jsonForResult.getMessage() != null && "".equals(jsonForResult.getMessage()) == false) {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                }
            } catch (Exception e) {
                Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<JsonForResult> call, Throwable t) {
            String msg = "网络异常!";
            if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
            UtilHelper.alertMsg(context, "错误", msg);
        }
    }

    /*根据疫苗列表中的vaccineId获取生产厂家的列表*/
    private void getGlobeManufacturesListFromManufacturesVaccineInfo() {
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("deptId", application.getDeptId());
        params.put("vaccineId", application.getVaccineId());
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.EMIAO(application.getBackSystem()));
        VaccineService vs = retrofit.create(VaccineService.class);
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = vs.getGlobeManufacturesListFromManufacturesVaccineInfo(token, params);
        jsonForResultCall.enqueue(new getGlobeManufacturesListFromManufacturesVaccineInfoCallback());
    }

    private class getGlobeManufacturesListFromManufacturesVaccineInfoCallback implements Callback<JsonForResult> {

        @Override
        public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
            try {
                JsonForResult jsonForResult = (JsonForResult) response.body();
                if (jsonForResult != null && jsonForResult.isSuccess() && jsonForResult.getData() != null) {
                    manufactureList = JSON.parseArray(jsonForResult.getData().toString(), Manufacture.class);
                } else {
                    if (jsonForResult != null && jsonForResult.getMessage() != null && "".equals(jsonForResult.getMessage()) == false) {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                }
            } catch (Exception e) {
                Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<JsonForResult> call, Throwable t) {
            String msg = "网络异常!";
            if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
            UtilHelper.alertMsg(context, "错误", msg);
        }
    }

    /*拿到生产厂家的Id后,根据manufacturerId和vaccineId,获取批号列表*/
    private void getVaccineLotsList() {
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("deptId", application.getDeptId());
        params.put("vaccineId", application.getVaccineId());
        params.put("manufacturerId", application.getManufacturerId());
        params.put("category", application.getCategory());
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.EMIAO(application.getBackSystem()));
        VaccineService vs = retrofit.create(VaccineService.class);
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = vs.getVaccineLotsList(token, params);
        jsonForResultCall.enqueue(new getVaccineLotsListCallback());
    }

    private class getVaccineLotsListCallback implements Callback<JsonForResult> {
        @Override
        public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
            try {
                JsonForResult jsonForResult = (JsonForResult) response.body();
                if (jsonForResult != null && jsonForResult.isSuccess() && jsonForResult.getData() != null) {
                    vaccineLotsList = JSON.parseArray(jsonForResult.getData().toString(), VaccineLots.class);
                } else {
                    if (jsonForResult != null && jsonForResult.getMessage() != null && "".equals(jsonForResult.getMessage()) == false) {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                }
            } catch (Exception e) {
                Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<JsonForResult> call, Throwable t) {
            String msg = "网络异常!";
            if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
            UtilHelper.alertMsg(context, "错误", msg);
        }
    }

    /*在获取批号的接口后,拿到propertyId,获取vService,和vPrice*/
    private void getUnitPriceByType(TextView addServicePrice, TextView addUnitPrice) {//deptId,priceBookMstId,vaccineId,manufacturerId,orderType: CHECK_ORDER,propertyId
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("deptId", application.getDeptId());
        params.put("vaccineId", application.getVaccineId());
        params.put("manufacturerId", application.getManufacturerId());
        params.put("priceBookMstId", application.getPriceBookMstId());
        params.put("orderType", "CHECK_ORDER");
        params.put("propertyId", application.getPropertyId());
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.EMIAO(application.getBackSystem()));
        VaccineService vs = retrofit.create(VaccineService.class);
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = vs.getUnitPriceByType(token, params);
        jsonForResultCall.enqueue(new getUnitPriceByTypeCallback(addServicePrice, addUnitPrice));
    }

    private class getUnitPriceByTypeCallback implements Callback<JsonForResult> {
        private TextView addServicePrice, addUnitPrice;

        public getUnitPriceByTypeCallback(TextView addServicePrice, TextView addUnitPrice) {
            this.addUnitPrice = addUnitPrice;
            this.addServicePrice = addServicePrice;
        }

        @Override
        public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
            try {
                JsonForResult jsonForResult = (JsonForResult) response.body();
                if (jsonForResult != null && jsonForResult.isSuccess() && jsonForResult.getData() != null) {
                    unitPrice = JSON.parseObject(jsonForResult.getData().toString(), UnitPrice.class);
                    addServicePrice.setText("服务费:"+String.valueOf(unitPrice.getVService()));
                    addServicePrice.setTextColor(getResources().getColor(R.color.billTextChoose));
                    addUnitPrice.setText("单价:"+String.valueOf(unitPrice.getVPrice()));
                    addUnitPrice.setTextColor(getResources().getColor(R.color.billTextChoose));
                } else {
                    if (jsonForResult != null && jsonForResult.getMessage() != null && "".equals(jsonForResult.getMessage()) == false) {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                }
            } catch (Exception e) {
                Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<JsonForResult> call, Throwable t) {
            String msg = "网络异常!";
            if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
            UtilHelper.alertMsg(context, "错误", msg);
        }
    }

    /*日常盘点,判断code是否符合,传deptId,vaccineId,manufacturerId,propertyId,vaccineLotsId,lotNumber,code*/
    private void checkCodeParam(String code) {//deptId,priceBookMstId,vaccineId,manufacturerId,orderType: CHECK_ORDER,propertyId
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("deptId", application.getDeptId());
        params.put("vaccineId", application.getVaccineId());
        params.put("manufacturerId", application.getManufacturerId());
        params.put("vaccineLotsId", inventory.getVaccineLotsId());
        params.put("lotNumber", inventory.getLotNumber());
        params.put("code", code);
        params.put("propertyId", application.getPropertyId());
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API(application.getBackSystem()));
        VaccineService vs = retrofit.create(VaccineService.class);
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = vs.checkCodeParam(token, params);
        jsonForResultCall.enqueue(new checkCodeParamCallback(code));
    }

    private class checkCodeParamCallback implements Callback<JsonForResult> {
        private String code;

        public checkCodeParamCallback(String code) {
            this.code = code;
        }

        @Override
        public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
            try {
                JsonForResult jsonForResult = (JsonForResult) response.body();
                if (jsonForResult != null && jsonForResult.isSuccess()) {
                    if (!contains(electCodeList, code)) {
                        ElectCodePackageVoList electCodePackageVoList = new ElectCodePackageVoList();
                        electCodePackageVoList.setElectCode(code);
                        electCodePackageVoList.setQuantity(String.valueOf(inventory.getQuantityOfSpec()));
                        electCodeList2.add(0, electCodePackageVoList);
                        electCodeList.add(0, electCodePackageVoList);
                        List<ElectCodePackageVoList> list = getPositionElectCodePackageVoList(electCodeList2);
                        codeAdapter = new CodeAdapter(list);
                        startItemRvVaccine.setAdapter(codeAdapter);
                    } else {
                        Toast.makeText(context, "该疫苗已经扫描过!", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    if (jsonForResult != null && jsonForResult.getMessage() != null && "".equals(jsonForResult.getMessage()) == false) {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                }
            } catch (Exception e) {
                Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<JsonForResult> call, Throwable t) {
            String msg = "网络异常!";
            if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
            UtilHelper.alertMsg(context, "错误", msg);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeScan(context);
        application.clearBill();//将bill里的数据清除
        inventoryList.clear();
    }
}